
const http = require('http');
const options=require('./settings');	//获取流量数据接口的参数设定
const mongo = require('./flowDB');      //更新数据库
const collect = require('./getCollector');  //获取采集器列表



function main() {
    // 获取采集器list
    let dbname = 'bg_collector_c';
    let dbFlow = 'bg_flow_data_c';
    collect(dbname,function (list) {
        for(let i= 0;i<list.length;i++){
            if(list[i].sim_number){
                let simNum = list[i].sim_number;
                let conditions = {"collector_id":list[i].collector_id};
                console.log(conditions);

                options.setUrl(simNum,function (obj) {//传入simNum设置请求参数
                    let data='';
                    console.log('请求的参数'+JSON.stringify(obj));

                    let req = http.request(obj, function(res) {//发送请求获取流量使用数据

                        res.setEncoding('utf8');
                        res.on('data', function (chunk) {
                            console.log('BODY: ' + chunk);
                            data+=chunk
                        });
                        res.on('end',()=>{
                            console.log('接收数据完成');
                            console.log(data);
                            let leftFlow = parseInt(data.result[0].gprs[0].left);
                            let usedFlow = parseInt(data.result[0].gprs[0].used);
                            let totalFlow = parseInt(data.result[0].gprs[0].total);
                            //更新流量剩余,使用情况
                            let update = {"left_flow":leftFlow,"used_flow":usedFlow};
                            //生成流量使用数组
                            let insertFlow = {'total_flow':totalFlow,'used_flow':usedFlow,'left_flow':leftFlow,'time':new Date(),'sim_number':simNum};
                            // 更新流量数据
                            mongo.updateFlow(conditions,update,insertFlow,dbname,dbFlow)
                        })
                    });

                    req.on('error', function(e) {
                        console.log('请求失败');
                        console.log('problem with request: ' + e.message);
                    });

                    // write data to request body
                    req.write('data\n');
                    req.write('data\n');
                    req.end();
                })

            }
        }
    })
}
main();
setInterval(main,10000);
const server = http.createServer(function (req,res) {
    console.log('有客户访问');
    console.log(req.url);
    res.writeHead(200,{'Content-type':'text/blain'});
    res.end();
})
server.listen(8088);




